package com.asktgapp.widget;

import android.content.Context;
import android.content.Intent;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.AttrRes;
import android.support.annotation.NonNull;
import android.support.annotation.Nullable;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.FrameLayout;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;
import android.widget.Toast;

import com.asktgapp.JGTool.Utils;
import com.asktgapp.R;
import com.asktgapp.eventbus.HomeEvent;
import com.asktgapp.model.IndexVO;
import com.asktgapp.model.NewHomeOneBean;
import com.asktgapp.modulebase.common.util.PreferencesUtil;
import com.asktgapp.modulebase.common.util.Util;
import com.asktgapp.user.activity.EngineerDetailActivity;
import com.asktgapp.user.activity.EngineerListActivity;
import com.asktgapp.user.activity.HomeServiceActivity;
import com.asktgapp.user.activity.IndustryInfoDetailActivity;
import com.asktgapp.user.activity.PhotoViewActivity;
import com.asktgapp.user.activity.WebViewActivity;
import com.asktgapp.utils.ImageDisplayUtil;

import java.util.ArrayList;
import java.util.List;

/**
 * time:2018/1/22
 * Create By ZhaoKai
 * Email: dczk@foxmail.com
 * Description:
 */

public class HomeBannerViewpPager extends FrameLayout {
    private ViewPager bannerViewPager;
    private LinearLayout ll_dot_group_banner;
    /**
     * Banner上一个被选中的小圆点的索引，默认值为0
     */
    private int preDotPositionBanner = 0;
    /**
     * Banner的切换下一个page的间隔时间
     */
    private long scrollTimeOffset = 4000;
    private MyHandler mHandler;
    private int currentPage = 0;
    private Context context;
    /**
     * 自动轮播viewpager
     **/
    private static final int AUTO_CHANGE_VIEWPAGER = 100;

    public HomeBannerViewpPager(@NonNull Context context) {
        super(context);
        this.context = context;
        initView();
    }


    public HomeBannerViewpPager(@NonNull Context context, @Nullable AttributeSet attrs) {
        super(context, attrs);
        this.context = context;
        initView();

    }

    public HomeBannerViewpPager(@NonNull Context context, @Nullable AttributeSet attrs, @AttrRes int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        this.context = context;
        initView();

    }

    private void initView() {
        View view = LayoutInflater.from(context).inflate(R.layout.banner_adapter, null, false);
        bannerViewPager = (ViewPager) view.findViewById(R.id.viewpager);
        ll_dot_group_banner = (LinearLayout) view.findViewById(R.id.ll_dot_group_banner);
        addView(view);

    }

    public void loadBannerData(List<NewHomeOneBean.BannerListBean> banners) {
        preDotPositionBanner = 0;
        int size = banners.size();
//        if (ll_dot_group_banner.getChildCount() == size) {
//            return;
//        }
        ll_dot_group_banner.removeAllViews();
        for (int i = 0; i < size; i++) {

            // 每循环一次添加一个点到线行布局中
            View dot = new View(context);
            dot.setBackgroundResource(R.drawable.selector_banner_dot);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(Utils.dp2px(context, 6), Utils.dp2px(context, 6));
            params.leftMargin = 10;
            dot.setEnabled(false);
            dot.setLayoutParams(params);
            ll_dot_group_banner.addView(dot); // 向线性布局中添加"点"
        }
        BannerAdapter bannerAdapter = new BannerAdapter(ll_dot_group_banner, banners);
        bannerViewPager.setAdapter(bannerAdapter);
        bannerViewPager.addOnPageChangeListener(bannerAdapter);

        ll_dot_group_banner.getChildAt(0).setSelected(true);
        bannerViewPager.setCurrentItem(0);
        if (mHandler != null)
            mHandler.removeCallbacksAndMessages(null);
        mHandler = new MyHandler(bannerViewPager);
        startBanner();
    }


    private class MyHandler extends Handler {
        private ViewPager mViewPager;

        public MyHandler(ViewPager mViewPager) {
            this.mViewPager = mViewPager;
        }

        @Override
        public void handleMessage(Message msg) {
            switch (msg.what) {
                case AUTO_CHANGE_VIEWPAGER:
                    if (mViewPager.getAdapter().getCount() > 1) {
                        int newIndex = mViewPager.getCurrentItem() + 1;
                        mViewPager.setCurrentItem(newIndex, true);
                        currentPage = newIndex;
                        // 每4秒钟发送一个message，用于切换viewPager中的图片
                        this.sendEmptyMessageDelayed(AUTO_CHANGE_VIEWPAGER, scrollTimeOffset);
                    }
                    break;
            }
            super.handleMessage(msg);
        }

        public ViewPager getmViewPager() {
            return mViewPager;
        }

    }

    private void startBanner() {
        if (mHandler == null)
            return;
        preDotPositionBanner = 0;
        mHandler.removeCallbacksAndMessages(null);
        mHandler.sendEmptyMessageDelayed(AUTO_CHANGE_VIEWPAGER, scrollTimeOffset);
    }

    public void onBannerResume() {
        if (mHandler != null) {
            mHandler.getmViewPager().setCurrentItem(currentPage);
            mHandler.removeCallbacksAndMessages(null);
            mHandler.sendEmptyMessageDelayed(AUTO_CHANGE_VIEWPAGER, 4000);
            preDotPositionBanner = 0;
        }
    }

    public void onBannerPause() {
        if (mHandler != null) {
            currentPage = mHandler.getmViewPager().getCurrentItem();
            // 停止viewPager中图片的自动切换
            mHandler.removeCallbacksAndMessages(null);
        }
    }

    /**
     * ViewPager的适配器
     */
    private class BannerAdapter extends PagerAdapter implements ViewPager.OnPageChangeListener {

        private LinearLayout llDotGroup;

        private List<NewHomeOneBean.BannerListBean> banners;

        public BannerAdapter(LinearLayout llDotGroup, List<NewHomeOneBean.BannerListBean> banners) {
            if (llDotGroup != null) {
                this.llDotGroup = llDotGroup;
            }
            if (banners != null && banners.size() > 0)
                this.banners = banners;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView((View) object);
        }

        @Override
        public Object instantiateItem(ViewGroup container, final int position) {
            int index = position % banners.size();
            View view = View.inflate(context, R.layout.item_home_banner, null);
            ImageView imageView = (ImageView) view.findViewById(R.id.iv_banner);
            final NewHomeOneBean.BannerListBean person = banners.get(index);
            ImageDisplayUtil.LoadNetImageWithUrl(imageView, context, person.getPic());
            // 为每一个page添加点击事件

            view.setOnClickListener(new MbanOnclickListener(person));

            container.addView(view);
            return view;
        }

        public class MbanOnclickListener implements OnClickListener {

            NewHomeOneBean.BannerListBean person;

            public MbanOnclickListener(NewHomeOneBean.BannerListBean person) {
                this.person = person;
            }

            @Override
            public void onClick(View v) {
                if (person == null)
                    return;
                if (person.getType() == 1) {
                    Intent intent = new Intent(context, WebViewActivity.class);
                    intent.putExtra("url", person.getPath());
                    intent.putExtra("type", 0);
                    context.startActivity(intent);
                } else if (person.getType() == 2) {
                    ArrayList list = new ArrayList<>();
                    list.add(person.getPic());
                    Intent intent = new Intent(context, PhotoViewActivity.class);
                    intent.putExtra("position", 0);
//                    intent.putExtra("type", 1);
                    intent.putStringArrayListExtra("imgs", list);
                    context.startActivity(intent);
                    //// TODO: 2018/3/12  看大图
                } else if (person.getType() == 3) {
                    if (person.getSkipType() == 0) {
                        Intent intent = new Intent(context, IndustryInfoDetailActivity.class);
                        intent.putExtra("id", person.getPath());
                        context.startActivity(intent);

                    } else if (person.getSkipType() == 1) {
                        Intent intent = new Intent(context, EngineerDetailActivity.class);
                        intent.putExtra("id", person.getPath());
                        context.startActivity(intent);
                    }
                } else if (person.getType() == 4) {//列表跳转
                    if (person.getSkipType() == 3) {//skipType=3代表工程师列表
                        HomeEvent.postEvent(3);
                    } else if (person.getSkipType() == 4) {//skipType=4代表上门服务列表
                        HomeEvent.postEvent(4);
                    }
                } else if (person.getType() == 5) {
                    Intent intent = new Intent(context, WebViewActivity.class);
                    intent.putExtra("url", person.getPath());
                    intent.putExtra("type", 1);
                    context.startActivity(intent);
                }


            }
        }

        @Override
        public int getCount() {
            if (banners.size() > 1) {
                return Integer.MAX_VALUE;
            } else {
                return 1;
            }
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }


        @Override
        public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

        }

        @Override
        public void onPageSelected(int position) {
//            Log.i("banner", "position：" + position);

            // 取余后的索引，得到新的page的索引
            int newPositon = position % banners.size();
//            Log.i("banner", "newPositon：" + newPositon);
            // 根据索引设置图片的描述
//            tvBannerTextDesc.setText(bannerTextDescArray[newPositon]);
            // 把上一个点设置为被选中
            if (llDotGroup.getChildAt(preDotPositionBanner) != null) {
                llDotGroup.getChildAt(preDotPositionBanner).setSelected(false);
            }
//            Log.i("banner", "preDotPositionBanner：" + preDotPositionBanner);
            // 根据索引设置那个点被选中
            if (llDotGroup.getChildAt(newPositon) != null) {
                llDotGroup.getChildAt(newPositon).setSelected(true);
            }

            // 新索引赋值给上一个索引的位置
            preDotPositionBanner = newPositon;
        }


        @Override
        public void onPageScrollStateChanged(int state) {

        }
    }

    public void setH(int h) {
        RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) bannerViewPager.getLayoutParams();
        params.height = h;
        bannerViewPager.setLayoutParams(params);
    }
}
